<template>
  <div class="container">
    <uv-navbar :placeholder="true" :autoBack="true">
      <template v-slot:left>
        <view class="uv-nav-slot flex alignCenter">
          <uv-icon name="arrow-left" size="19"></uv-icon>
          <view class="user flex alignCenter">
            <uv-image :src="info.avatar" width="30px" height="30px" shape="circle"></uv-image>
            <view class="data">
              <view class="name fz14 bold">{{info.nickname}}</view>
              <view class="desc fz12">{{info.ageYear}} {{info.industry}}</view>
            </view>
          </view>
        </view>
      </template>
      <template v-slot:right>
        <view class="uv-nav-slot flex alignCenter">
          <uv-button text="取消关注" @click="toFollow" color="#EC7272" size="mini" shape="circle" v-if="isFollow"></uv-button>
          <uv-button text="关注" @click="toFollow" color="#EC7272" size="mini" shape="circle" v-else></uv-button>
          <view style="margin-left:5px">
            <uv-icon name="share-square" size="20"></uv-icon>
          </view>
        </view>
      </template>
    </uv-navbar>

    <uv-swiper :list="info.imageContent" height="60vh" indicator circular></uv-swiper>

    <view class="comment flex alignCenter">
      <uv-input @confirm="send" @blur="blur" :focus="focus" placeholderStyle="color:'#6C757D'" :placeholder="placeholder_format" v-model="commentParams.comment" :customStyle="sendStyle">
        <template v-slot:suffix>
          <uv-image src="https://meet-city.oss-cn-beijing.aliyuncs.com/images/2024/11/13/17314785817436362.png" width="20px" height="20px"></uv-image>
        </template>
      </uv-input>
      <view class="like flex alignCenter fz14" @click.stop="likeFunc(info,1)">
        <uv-icon name="heart" v-if="info.hasLiked==0" size="35" color="#E59840"></uv-icon>
        <uv-icon name="heart-fill" color="#E59840" v-else size="35"></uv-icon>
        <text v-if="info.likeCount" class="fz16 bold" style="color:#E59840">{{info.likeCount}}</text>
      </view>
    </view>

    <view class="vote-item">
      <!-- 评价 -->
      <view v-if="info.publishType==3">
        <view class="voteName fz14 bold ">
          <text style="color:#3798F2" v-if="info.votedName">#{{info.votedName}}</text>
          <text style="color:#3798F2;margin-left:10px">{{info.votedPrice}}</text>
          {{info.textContent}}
        </view>
        <view class="voteName fz14 bold">发起投票</view>

        <view class="progress">
          <view class="progressLine flex positionRelative">
            <view class="left shrink " v-if="percentage(info,'likeVoteCount')" :style="`width:${percentage(info,'likeVoteCount')}%`">
              <view style="padding-left:15px;">
                <view class="bold fz14">{{percentage(info,'likeVoteCount')}}%</view>
                <view class="fz12">想要</view>
              </view>
            </view>

            <view class="vsIcon" :style="vsIconStyle(info)" v-if="![0,100].includes(percentage(info,'likeVoteCount'))">
              <view class="image">
                <uv-image src="https://meet-city.oss-cn-beijing.aliyuncs.com/images/2024/11/15/17316368611573548.png" width="30px" mode="widthFix"></uv-image>
              </view>
            </view>

            <view class="right shrink flex justifyFlexEnd" v-if="percentage(info,'dislikeVoteCount')" :style="`width:${percentage(info,'dislikeVoteCount')}%`">
              <view style="padding-right:15px;">
                <view class="bold fz14">{{percentage(info,'dislikeVoteCount')}}%</view>
                <view class="fz12">不想要</view>
              </view>
            </view>
          </view>

          <view class="flex alignCenter justifyBetween" style="margin-bottom:10px;">
            <view class="flex alignCenter avatarGroup">
              <uv-avatar-group :urls="info.voteLogos" size="20" gap="0.4"></uv-avatar-group>
              <text>+{{info.voteLogos&&info.voteLogos.length}}参加</text>
            </view>
            <text class="fz12" style="color: #3f38dd">还有{{info.voteEndTime}}天结束</text>
          </view>

          <view class="flex alignCenter justifyBetween" v-if="info.hasVoted==0">
            <view class="btn" @click.stop="toVoted(info,1)">
              <uv-button text="赞成" shape="circle" color="#266EFF"></uv-button>
            </view>
            <view class="btn" @click.stop="toVoted(info,0)">
              <uv-button text="反对" shape="circle" color="#FC6C6C"></uv-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 动态 -->
      <view v-else class="dynamic">
        <view class="intro fz14">
          <uv-parse :content="replaceIfMatch(info.textContent,info.movementJsons,'#429CEE')"></uv-parse>
        </view>
        <view class="topicDiv" v-if="info.topic && info.topic.id" @click.stop="proxy.$utils.toLink(`/packagePages/topic/topicDetails?id=${info.topic.id}`)">
          <view class="text">#{{info.topic.topicName}}</view>
        </view>
      </view>

      <view class="content">
        <view class="user-info flex" v-for="(ele, index) in list" :key="index" @click="comClick(ele)">
          <uv-avatar :src="ele.avatar" size="33"></uv-avatar>
          <view class="wrap">
            <view class="flex alignCenter">
              <text class="fz14">{{ele.nickname}}
                <text class="time fz12">{{ele.createDate}}</text>
              </text>
            </view>
            <view class="intro fz14"> {{ele.content}}</view>
            <view class="like flex justifyStart alignCenter fz14 bold" @click.stop="likeFunc(ele)">
              <uv-icon name="heart" v-if="ele.hasLiked==0" color="#DD191D"></uv-icon>
              <uv-icon name="heart-fill" v-else color="#DD191D"></uv-icon>
              <text>{{ele.likeCount}}</text>
            </view>

            <!-- 二级 -->
            <view class="sec flex" v-for="(sec,idx) in ele.replies?ele.replies:[]" :key="idx" @click.stop="comClick(sec)">
              <uv-avatar :src="sec.avatar" size="25"></uv-avatar>
              <view class="wrap">
                <view class="nickname fz14">
                  <view class="flex alignCenter flexWrap">
                    {{sec.nickname}}
                    <text v-if="sec.fromUserId  && (sec.parentId != ele.id)">回复 {{sec.fromNickname}}</text>
                    <text class="time fz12">{{ele.createDate}}</text>
                  </view>
                </view>
                <view class="intro fz14">{{sec.content}}</view>
                <view class="like flex justifyStart alignCenter fz14" @click.stop="likeFunc(sec)">
                  <uv-icon name="heart" v-if="sec.hasLiked==0" color="#DD191D"></uv-icon>
                  <uv-icon name="heart-fill" v-else color="#DD191D"></uv-icon>
                  {{sec.likeCount}}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();

let id = "";
let commentParams = ref({
  movementId: "",
  parentId: "",
  comment: "",
});
let focus = ref(false);
let params = {
  movementId: "",
  page: 1,
  pageSize: 10,
  sort: "desc",
};
let list = ref([]);
let totalPages = 0;
let loading = ref(false);
let sendStyle = computed(() => {
  return {
    background: "#F8F8F8",
    borderColor: "#F2F2F2 !important",
  };
});
let replyNickname = ref("");
let isFollow = ref(false); //是否关注
let info = ref({});

onLoad(async (e) => {
  id = e.id;
  params.movementId = e.id;
  getComment();
  await getInfo();
  getFollowStatus();
});

onShow(() => {
  uni.setNavigationBarColor({
    frontColor: "#000000", //文字颜色
    backgroundColor: "#fff8ee", //底部背景色
  });
});

let placeholder_format = computed(() => {
  return replyNickname.value ? `回复 ${replyNickname.value}` : "请输入";
});

function replaceIfMatch(inputString, friends, colorValue) {
  // 正则表达式匹配 @$与$ 之间的字符串
  const regex = /\@\$([0-9]+)\$/g;
  // 使用 replace 方法进行替换
  const resultString = inputString.replace(regex, (match, friendId) => {
    // 找到对应的 friendId
    const friend = friends.find((f) => f.friendId == Number(friendId));
    // 如果找到了对应的好友，替换成带色值的 @nikeName；否则不做替换
    return friend
      ? `<span style="color: ${colorValue};">@${friend.nikeName}</span>`
      : match;
  });
  return resultString;
}

function percentage(item, type) {
  let a = item[type];
  let b = item.likeVoteCount + item.dislikeVoteCount;
  if (a == 0 && b == 0) return 50;
  if (a == 0) return 0;
  return (a / b) * 100;
}

function vsIconStyle(item) {
  let a = percentage(item, "likeVoteCount");
  if ([1, 100].includes(a)) {
  } else {
    return { left: "calc(50% - 20px)" };
  }
}

async function toVoted(item, voteType) {
  if (info.hasVoted == 1) return;
  await proxy.$apis.movementsVote({ id: info.id, voteType });
  proxy.$utils.showToast("投票成功");
  getInfo();
}

async function getInfo() {
  info.value = await proxy.$apis.movementsDetails(id);
  console.log("详情", info.value);
}

function blur() {
  replyNickname.value = "";
  focus.value = false;
}

function comClick(ele) {
  commentParams.value.parentId = ele.id;
  replyNickname.value = ele.nickname;
  focus.value = true;
}

async function getComment() {
  let resp = await proxy.$apis.comments(params);
  let arr = [...list.value];
  if (resp.records.length) {
    arr = proxy.$utils.filterArr([...arr], resp.records, "id");
  }
  list.value = arr;
  totalPages = resp.totalPages;
  console.log("评论", list.value);
}

let send = async () => {
  try {
    loading.value = true;
    commentParams.value.movementId = id;
    await proxy.$apis.sendComments(commentParams.value);
    proxy.$utils.showToast("评论成功");
    getComment();
  } catch (error) {
    console.log("啥问题", error);
  } finally {
    replyNickname.value = "";
    commentParams.value = {
      movementId: "",
      parentId: "",
      comment: "",
    };
    loading.value = false;
    focus.value = false;
  }
};

async function likeFunc(item, type?) {
  if (type) {
    await counter.toLike(item.hasLiked, item.id, type);
  } else {
    await counter.toLike(item.hasLiked, item.id);
  }
  if (item.hasLiked) {
    proxy.$utils.showToast("取消点赞成功");
  } else {
    proxy.$utils.showToast("点赞成功");
  }
  getComment();
  getInfo();
}

async function toFollow() {
  await toFollowFunc();
  getFollowStatus();
}

async function toFollowFunc() {
  //已关注
  if (isFollow.value) {
    await proxy.$apis.userUnFocus({ friendId: info.value.userId });
    proxy.$utils.showToast("已取消关注");
  } else {
    await proxy.$apis.contacts({ friendId: info.value.userId });
    proxy.$utils.showToast("已成功关注");
  }
}

//关注状态
async function getFollowStatus() {
  isFollow.value = await proxy.$apis.attentionToIt({
    friendId: info.value.userId,
  });
}
</script>



<style lang="scss" scoped>
.container {
  padding-bottom: 80px;
  .user {
    .data {
      margin-left: 5px;
      .name {
        color: #3d68b4;
      }
      .desc {
        color: #d3d3d3;
      }
    }
  }
  .comment {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    padding: 15px 15px 25px 15px;
    z-index: 1;
    .like {
      margin-left: 10px;
      width: 13vw;
    }
  }
  .vote-item {
    width: calc(100% - 30px);
    margin: 0 auto 15px;
    background: white;
    border-radius: 10px;
    .dynamic {
      .intro {
        padding: 15px 0;
        font-size: 14px;
      }
      .topicDiv {
        font-size: 14px;
        background-color: #f1f7ff;
        color: #429cee;
        padding: 5px 15px;
        border-radius: 15px;
        display: inline-block;
      }
    }
    .avatarGroup {
      text {
        font-size: 12px;
        color: #3f38dd;
        margin-left: 10px;
      }
    }
    .voteName {
      margin-top: 10px;
    }
    .progress {
      border-radius: 10px;
      margin: 15px 0;
      .btn {
        width: calc((100% - 15px) / 2);
      }
      .progressLine {
        height: 40px;
        color: white;
        margin-bottom: 10px;
        border-radius: 20px;
        overflow: hidden;
        .left {
          background-color: #266eff;
        }
        .right {
          background-color: #fc6c6c;
        }
        .vsIcon {
          position: absolute;
          top: 0;
          bottom: 0;
          left: 50px;
          background: white;
          border-radius: 50%;
          width: 40px;
          height: 40px;
          .image {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }
  .content {
    padding: 15px;
  }

  .user-info {
    padding: 15px;
    .wrap {
      margin-left: 10px;
      width: 100%;
      .desc {
        color: #999999;
        padding: 3px 0 10px;
      }
      .time {
        color: #757d85;
        margin-left: 5px;
      }
      .intro {
        color: #202020;
        padding: 5px 0 7px;
      }
      .like {
        text {
          margin-left: 3px;
        }
      }
      .sec {
        margin-top: 15px;
      }
    }
  }
}
</style>

